import React,{useState,useEffect,useRef} from 'react'
interface Api<T> {
    (p: T): Promise<{ items: any[]; page: number; pageSize: number }>;
   }
   /* 接⼝⼊参定义 */
   interface Params {
    id: number;
    page: number;
    pageSize: number; }
   /* ListItems接⼝可以直接使⽤，⽆需关⼼具体实现 */
const ListItems: Api<Params> = async (
    p: Params,
   ) => api('/listItems', GET, p);
export default function useItemList() {
    const timer = useRef(null)
    const [id,setId] = useState(1)
    const [page,setPage] = useState(1)
    const [pageSize,setPageSize] = useState(10)
    const [params,setParams]:any = useState()
    const [data,setData] = useState([])
    const [loading,setLoading] = useState(false)
    useEffect(()=>{
        let param = {
            id:id,
            page:page,
            pageSize:pageSize
        }
        setParams(params)
    },[])
    useEffect(()=>{
        console.log(page)
        if(JSON.stringify(params) !== '{}'){
            let param = {...params,page:page}
            setParams(param)
        }
       
    },[page])
    useEffect(()=>{
        console.log(pageSize)
        if(JSON.stringify(params) !== '{}'){
            let param = {...params,pageSize:pageSize}
            setParams(param)
        }
    },[pageSize])
    useEffect(()=>{
        if(JSON.stringify(params) !== '{}'){
            if(timer.current !== null) {
                clearTimeout(timer.current)
                timer.current = null
            }
            setLoading(true)
            timer.current = setTimeout(()=>{
                ListItems(params).then((res) =>{
                    if(res.code == 200){
                        setLoading(false)
                        if(params.page === page && params.pageSize === pageSize){
                            setData(res.data)
                        }
                    } else {
                        throw(res)
                    }
                }).catch(err =>{
                    console.log(err)
                    setLoading(false)
                })
            },0)
        }
    },[params])
    return [data,loading,setPage,setPageSize]
}
